package io.github.jyrmc.gmcp.generate

import io.github.jyrmc.gmcp.common.FreemarkerConstant
import io.github.jyrmc.gmcp.utils.PrintInfoUtil
import freemarker.template.Configuration
import freemarker.template.Template
import io.github.jyrmc.gmcp.enums.FileStrategyType
import java.io.*
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.*

/**
 *
 * @描述：生成工具类
 * @时间：2021/3/1 5:30 下午
 * @作者：jy
 * @公司：贵州中测信息技术有限公司
 */
object GenerateJavaUtils {

    /**
     * 生成相应结果实体-freemarker模板
     */
    fun freemarkerGenerate(
        fileGenStrategy: FileStrategyType,
        frameworkType: String,
        config: Configuration,
        projectPath: String,
        languageType: String,
        packageName: String,
        author: String,
        enableGenerateDoc: Boolean
    ) {
        val createTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
        val fileName = "GenerateCodeUtils.${if (languageType == "java") FreemarkerConstant.JAVA_FILE_SUFFIX else FreemarkerConstant.KOTLIN_FILE_SUFFIX}"
        val fileFullPath =
            "${projectPath}/src/main/${languageType}/${packageName.replace(".", "/")}/utils/${fileName}"

        val file = File(fileFullPath)
        if (file.exists()) {
            println("message: file [${fileName}] is exists.")
            return
        }
        if (!file.exists()) {
            file.parentFile.mkdirs()

            PrintInfoUtil.printCreateFold(file.parentFile.absolutePath)
        }

        var dataMap: MutableMap<String, Any?> = mutableMapOf()
        dataMap["basePackage"] = packageName
        dataMap["author"] = author
        dataMap["createTime"] = createTime
        dataMap["enableGenerateDoc"] = enableGenerateDoc

        val template: Template = if (languageType == "java") {
            config.getTemplate(
                "java/$frameworkType/GenerateCodeUtils.java.ftl",
                "UTF-8"
            )
        } else {
            config.getTemplate(
                "kotlin/$frameworkType/GenerateCodeUtils.kt.ftl",
                "UTF-8"
            )
        }

        val out: Writer = BufferedWriter(OutputStreamWriter(FileOutputStream(fileFullPath), StandardCharsets.UTF_8))
        template.process(dataMap, out)
        out.flush()
        out.close()

        PrintInfoUtil.printCreateFile(fileFullPath)
    }
}